package com.zhangc.blog.admin.service;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangc.blog.admin.entity.BlogInfoEntity;
import com.zhangc.blog.admin.entity.BlogTagRelationEntity;
import com.zhangc.blog.admin.mapper.BlogTagRelationMapper;

@Service
public class BlogTagRelationServiceImpl extends ServiceImpl<BlogTagRelationMapper, BlogTagRelationEntity> {

    @Autowired
    private BlogTagRelationMapper blogTagRelationMapper;

    @Transactional(rollbackFor = Exception.class)
    public void removeAndsaveBatch(List<Integer> blogTagIds, BlogInfoEntity blogInfo) {
        Long blogId = blogInfo.getBlogId();
        List<BlogTagRelationEntity> list = blogTagIds.stream().map(blogTagId -> new BlogTagRelationEntity()
                .setTagId(blogTagId)
                .setBlogId(blogId)).collect(Collectors.toList());
        blogTagRelationMapper.delete(new QueryWrapper<BlogTagRelationEntity>()
                .lambda()
                .eq(BlogTagRelationEntity::getBlogId, blogInfo.getBlogId()));
        for (BlogTagRelationEntity item : list) {
            blogTagRelationMapper.insert(item);
        }
    }
}
